﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using System.Security.Principal;
using System.Net.Battlefield3;
using AwpAdmin.Web.Models;

namespace AwpAdmin.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //create roles
            AddRole("Manager"); //full control
            AddRole("Admin"); //only server administration
            AddRole("Ingame"); //used only for ingame interface
        }

        void AddRole(string name)
        {
            if (!Roles.RoleExists(name)) Roles.CreateRole(name);
        }
    }

    public static class RconProvider
    {
        //will return either a logged in rconclient or not logged in based on p
        //will also need to accept a model containing rcon data
        public static LightRconClient GetClient(ServerRcon rcon, IPrincipal p)
        {
            LightRconClient newClient = new LightRconClient()
            {
                Address = rcon.Address,
                Port = rcon.Port
            };

            try
            {
                newClient.Connect();
            }
            catch (Exception)
            {
                return null; //TODO: consider better solution
            }

            if (p.IsInRole("Admin") || p.IsInRole("Manager")) newClient.LogOn(rcon.Password);

            return newClient;
        }
    }
}